package com.yl.module.common.listener;

import com.alibaba.fastjson.JSON;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.Subscribe;
import com.yl.module.common.service.IMailService;
import com.yl.module.common.vo.TextMailForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @Todo
 * @Author jiangtao
 * @CreateBy 2020-06-15 5:14 PM
 * @UpdateBy jiangtao
 * @Version v1.0
 */
@Slf4j
@Component
public class MailEventBusListener {

    @Autowired
    private AsyncEventBus asyncEventBus;

    @Autowired
    private IMailService mailService;

    /**
     * 注册服务类
     */
    @PostConstruct
    public void init() {
        asyncEventBus.register(this);
    }

    @PreDestroy
    public void destroy() {
        asyncEventBus.unregister(this);
    }

    /**
     * 线程安全，消费 文本消息
     *
     * @param form
     */
    @AllowConcurrentEvents
    @Subscribe
    public void sendTextMail(TextMailForm form) {
        log.debug(JSON.toJSONString(form));
        mailService.sendSimpleMail(
                form.getTo(),
                form.getSubject(),
                form.getContent()
        );
    }

}
